package com.smallcr.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.smallcr.constant.HttpStatusEnum;

import javax.servlet.http.HttpServletRequest;


public class ResponseBodyResult {

	private static Logger logger = LogManager.getLogger();;

	public static ResponseResult success(String msg, Object data) {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), msg, HttpStatusEnum.SUCCESS.getDescription(), data);
	}

	public static ResponseResult success(Object data) {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMsg(),
				HttpStatusEnum.SUCCESS.getDescription(), data);
	}

	public static ResponseResult success() {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), HttpStatusEnum.SUCCESS.getMsg(),
				HttpStatusEnum.SUCCESS.getDescription());
	}

	public static ResponseResult success(String msg) {
		return returnObject(HttpStatusEnum.SUCCESS.getCode(), msg, HttpStatusEnum.SUCCESS.getDescription());
	}

	public static ResponseResult fail(String msg) {
		return returnObject(HttpStatusEnum.SERVER_FAIL.getCode(), msg, HttpStatusEnum.SERVER_FAIL.getDescription());
	}

	public static ResponseResult fail(int code, String msg) {
		return returnObject(code, msg, HttpStatusEnum.SERVER_FAIL.getDescription());
	}

	public static ResponseResult error(String msg, Exception e) {
		return returnObject(msg, e);
	}

	private static ResponseResult returnObject(int code, String msg, String memo, Object data) {
		if (logger.isDebugEnabled()) {
			logger.info(msg);
		}
		return new ResponseResult(code, DateUtils.getSysTimestamp().toString(), memo, msg, data);

	}

	public static ResponseResult returnObject(int code, String msg, String memo) {
		if (logger.isDebugEnabled()) {
			logger.info(msg);
		}
		return new ResponseResult(code, DateUtils.getSysTimestamp().toString(), memo, msg);
	}

	/**
	 *@Title: returnObject
	 *@Description: 定义接口异常返回值，同时记录错误日志
	 *@param:  msg
	 *@param:  exception
	 *@return: ResponseResult
	 *@throws
	 */
	private static ResponseResult returnObject(String msg, Exception exception) {
		HttpServletRequest request = RequestContextHolder.getHttpRequest();
		logger.error("***************************start recording error logs[***********************************");
		logger.error("request url:{}", request.getRequestURI());
		logger.error("request params:{}", request.getParameterMap());
		logger.error("localizedMessage:{}",  exception.getLocalizedMessage());
		logger.error("some errors occured,as follows:{}", DataUtil.getExceptionMsg(exception));
		logger.error("***************************end recording error logs****************************************");
		return new ResponseResult(HttpStatusEnum.SERVER_ERROR.getCode(), DateUtils.getSysTimestamp().toString(),
				HttpStatusEnum.SERVER_ERROR.getDescription(), msg);
	}
}
